package cloudspace.vm.javassist;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javassist.ClassPool;
import javassist.CtClass;


/**
 * A factory for creating Translator objects. This stores configuration options
 * for the creation of a configurable translator.
 */
public class TranslatorProvider
{

    /** The eef singleton. */
    private static TranslatorProvider eefSingleton = new TranslatorProvider();

    /** The translator configs. */
    private ConfigParser translatorConfig;


    /**
     * Instantiates a new translator factory.
     */
    private TranslatorProvider()
    {
    }


    /**
     * Gets the expr editor factory.
     * 
     * @return the expr editor factory
     */
    public static TranslatorProvider getExprEditorFactory()
    {
        return eefSingleton;
    }


    /**
     * Adds the config file.
     * 
     * @param userFile
     *            the user file
     * 
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void addConfigFile( File userFile, ClassPool proxyPool )
        throws IOException
    {
        translatorConfig = new ConfigParser( userFile, proxyPool );
    }


    /**
     * Gets a list of configurable translators from the configurations
     * registered.
     * 
     * @return the translators
     * 
     * @throws MalformedConfigurationException
     *             the malformed configuration exception
     */
    public List<ConfigurableTranslatorLoader> getTranslators()
        throws MalformedConfigurationException
    {
        List<ConfigurableTranslatorLoader> translators = new ArrayList<ConfigurableTranslatorLoader>();
        try
        {
            translatorConfig.autoUpdate();
        }
        catch ( IOException e )
        {
            translatorConfig = null;
            throw new MalformedConfigurationException( "The configuration file has been removed from the system" );
        }
        ConfigurableTranslatorLoader configTrans = new ConfigurableTranslatorLoader( translatorConfig );
        translators.add( configTrans );

        return translators;
    }


    public CtClass getProxy( String className )
    {
        return translatorConfig.getProxy( className );
    }

}
